import axios, { type AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000
})

interface PendingTask {
  config: AxiosRequestConfig
  resolve: Function
}

/**
 * 每次发送请求前，在header里加上authorization ，带上access_token
 */
axiosInstance.interceptors.request.use((config) => {
  const accessToken = localStorage.getItem('access_token')
  if (accessToken) {
    config.headers.Authorization = `Bearer ${accessToken}`
  }
  return config
})

axiosInstance.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    if (!error.response) {
      return Promise.reject(error)
    }
    let { data, config } = error.response

    // 当响应码是401的时候，就刷新token，刷新失败提示错误信息，如何跳转登录页
    if (data.code === 401 && !config.url.includes('/user/refresh')) {
      const res = await refreshToken()
      if (res.status === 200 || res.status === 201) {
        return axiosInstance(config)
      } else {
        ElMessage.error(res.data.data)
        setTimeout(() => {
          window.location.href = '/login'
        }, 1500)
      }
    } else {
      return error.response
    }
  }
)

async function refreshToken() {
  const res = await axiosInstance.get('/user/refresh', {
    params: {
      refreshToken: localStorage.getItem('refresh_token')
    }
  })
  localStorage.setItem('access_token', res.data.access_token || '')
  localStorage.setItem('refresh_token', res.data.refresh_token || '')
  return res
}

export default axiosInstance
